from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from task.models import Task


# Create your views here.
@login_required(login_url='/account/login/')
@csrf_exempt
def show_task(request):
    if request.method =='GET':
        return render(request, 'show_task.html')
    else:
        try:
            tasks = Task.objects.filter(user=request.user).order_by('deadline')
            return JsonResponse({'data':list(tasks.values()),'msg':'成功'})
        except Exception as e:
            return JsonResponse({'msg':'获取信息失败'})

@login_required(login_url='/account/login/')
@require_POST
@csrf_exempt
def add_task(request):
    new_task = Task(user=request.user,
                    body=request.POST.get('body'),
                    deadline=request.POST.get('ddl'))
    new_task.save()
    return JsonResponse({'msg':'添加成功'})

@login_required(login_url='/account/login/')
@require_POST
@csrf_exempt
def task_check(request):
    t_id = request.POST.get('t_id')
    task = Task.objects.get(pk=t_id)
    task.status = 1
    task.save()
    return JsonResponse({'msg':'success'})


@login_required(login_url='/account/login/')
@require_POST
@csrf_exempt
def del_task(request):
    task = Task.objects.get(pk=request.POST.get('t_id'))
    task.delete()
    return JsonResponse({'msg':'删除成功'})